package com.wellview.template.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sun.misc.BASE64Encoder;

/**
 * Created by Administrator on 2017/9/27 0027.
 */

public class FileUtil {
    private static File apkname;
    public static String TAG = "FileUtil";
    public static String fileCache = "DaZhuDownLoad/apk";
    private static File apkFile;
    private static HashMap<Integer,Call> map = new HashMap<>();
    public static void downLoadFile(final Context context , final String url, final String fileName, final String dir, final DownLoadCallBack callBack, final int id){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                Call call = mOkHttpClient.newCall(request);
                map.put(id,call);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        if (callBack != null){
                            callBack.downLoadError(e);
                        }
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        apkFile = getOwnCacheDirectory(context, dir);
                        apkname = new File(apkFile, fileName);
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;
                        try {
                            long total = response.body().contentLength();

                            long current = 0l;
                            is = response.body().byteStream();
                            fos = new FileOutputStream(apkname);

                            while ((len = is.read(buf)) != -1) {
                                current += len;
                                fos.write(buf, 0, len);
//                                Log.e(TAG, "current------>" + current+"   total------>" + total);
                                int currentPersent= (int) (current * 1.0f / total * 100);
                                Log.e(TAG,"currentPersent------>" + currentPersent);
                                callBack.downLoadProgress(currentPersent);
                                if (currentPersent == 100){
                                    callBack.downLoadSuccess(apkname.getAbsolutePath());
                                }
                            }

                            fos.flush();
                        } catch (IOException e) {
                            if (callBack != null){
                                callBack.downLoadError(e);
                            }
                            Log.e(TAG, e.toString());
                        } finally {
                            try {
                                if (is != null) {
                                    is.close();
                                }
                                if (fos != null) {
                                    fos.close();
                                }
                            } catch (IOException e) {
                                if (callBack != null){
                                    callBack.downLoadError(e);
                                }
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                });
            }

        });
        thread.start();
    }

    public static void downLoadFile(final Context context , final String url, final String fileName, String dir,int id){
        downLoadFile(context,url,fileName,dir,null,id);
    }

    public static void downLoadFile(final Context context , final String url,String fileName,int id){
        downLoadFile(context,url,fileName,fileCache,null,id);
    }
    public static void downLoadFile(final Context context , final String url,String fileName,DownLoadCallBack callBack,int id){
        downLoadFile(context,url,fileName,fileCache,callBack,id);
    }


    public static File getOwnCacheDirectory(Context context, String cacheDir) {
        File appCacheDir = null;
        if("mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
            appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir);
            Log.e("StorageUtil","appCacheDir: "+appCacheDir);
        }

        if(appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) {
            appCacheDir = context.getCacheDir();
        }

        return appCacheDir;
    }
    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
        return perm == 0;
    }

    public static void cancelCall(int id){
        Call call = map.get(id);
        if (call != null){
            boolean canceled = call.isCanceled();
            if (canceled){
                return;
            }
            call.cancel();
        }
    }

    public interface DownLoadCallBack {
        void downLoadError(Exception e);

        void downLoadSuccess(String fileLocation);

        void downLoadProgress(int percent);
    }


    public static void updateApk(Context context,File apkFile) {
//        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
//            Uri apkUri = FileProvider.getUriForFile(context, "com.view.dazhu.dazhu.fileprovider", apkname);//在AndroidManifest中的android:authorities值
//            Intent install = new Intent(Intent.ACTION_VIEW);
//            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
//            context.startActivity(install);
//        } else{
//            Intent install = new Intent(Intent.ACTION_VIEW);
//            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
//            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(install);
//        }

        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        context.startActivity(install);
    }


    public static final String SDK_CACHE_PATH = "aliCloud";

    public FileUtil() {
    }

    public static File getExternalStorageDirectory(Context var0, String var1) {
        File var2;
        if(isCanUseSDCard()) {
            var2 = new File(Environment.getExternalStorageDirectory(), var1);
        } else {
            var2 = new File(getCacheDir(var0), var1);
        }

        if(!var2.exists()) {
            var2.mkdirs();
        }

        return var2;
    }

    public static File getCachePath(Context var0,String dir) {
        return getExternalStoragePublicDirectory(var0, dir);
    }

    public static File getExternalStoragePublicDirectory(Context var0, String var1) {
        File var2;
        if(isCanUseSDCard()) {
            var2 = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), var1);
        } else {
            var2 = new File(getCacheDir(var0), var1);
        }

        if(!var2.exists()) {
            var2.mkdirs();
        }

        return var2;
    }

    public static boolean isCanUseSDCard() {
        return Environment.getExternalStorageState().equals("mounted");
    }

    public static File getCacheDir(Context var0) {
        File var1;
        if(isCanUseSDCard()) {
            if(Build.VERSION.SDK_INT >= 8) {
                var1 = var0.getExternalCacheDir();
            } else {
                var1 = a(var0);
            }
        } else {
            var1 = var0.getCacheDir();
        }

        if(var1 != null && !var1.exists()) {
            var1.mkdirs();
        }

        return var1;
    }

    public static File getExternalCacheDir(Context var0) {
        File var1 = null;
        if(isCanUseSDCard()) {
            if(Build.VERSION.SDK_INT >= 8) {
                var1 = var0.getExternalCacheDir();
            } else {
                var1 = a(var0);
            }
        }

        if(var1 != null && !var1.exists()) {
            var1.mkdirs();
        }

        return var1;
    }

    private static final File a(Context var0) {
        return new File(Environment.getExternalStorageDirectory(), "/Android/data/" + var0.getApplicationInfo().packageName + "/cache/");
    }

    public static void copyStream(InputStream var0, OutputStream var1) throws IOException {
        copyStream(var0, var1, true);
    }

    public static void copyStream(InputStream var0, OutputStream var1, boolean var2) throws IOException {
        byte[] var3 = new byte[8192];

        int var4;
        while(!Thread.interrupted() && (var4 = var0.read(var3, 0, 8192)) != -1) {
            var1.write(var3, 0, var4);
        }

        var1.flush();
        if(var2) {
            var1.close();
        }

    }

    public static String generate(String var0) {
        return String.valueOf(var0.hashCode());
    }

    /**
     * 通过Uri返回File文件
     * 注意：通过相机的是类似content://media/external/images/media/97596
     * 通过相册选择的：file:///storage/sdcard0/DCIM/Camera/IMG_20150423_161955.jpg
     * 通过查询获取实际的地址
     * @param uri
     * @return
     */
    public static File getFileByUri(Context context,Uri uri) {
        String path = "";
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (!TextUtils.isEmpty(path)) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null,null );
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (!TextUtils.isEmpty(path)) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(uri, proj,null ,null ,null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
            Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null ;
    }


    /**
     * 将文件转成base64 字符串
     * @param path文件路径
     * @return  *
     * @throws Exception
     */

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);;
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
}
